<?php
/**
 * ab 并发测试swoole提升性能的各种方式
 * 分别测试了：
 * 无数据库查询；
 * pdo mysql查询
 * swoole mysql协程客户端查询；
 * swoole pdo mysql连接池查询；
 * 一键协程查询（使用一键协程需要注意：头部需要添加Co::set(['hook_flags' => SWOOLE_HOOK_TCP]);和http对象开启协程$http->set(['enable_coroutine' => true]);）
 *
 */

$pool = new Swoole\Database\PDOPool((new Swoole\Database\PDOConfig)
    ->withHost('127.0.0.1')
    ->withPort(5141)
    ->withDbName('test')
    ->withCharset('utf8mb4')
    ->withUsername('root')
    ->withPassword('Wang659096.')
    , 10);

$http = new Swoole\Http\Server('127.0.0.1', 9501);

$http->on('start', function ($server) {
    echo "Swoole Http server start!" . PHP_EOL;
});

$http->on('request', function ($request, $response) use ($pool) {
    $response->header('Content-Type', 'text/plain');

    //没有mysql查询 ab -n 1000 -c 10  result:14030.36 [#/sec] (mean)

    //正常pdo连接mysql ab -n 1000 -c 10  result: 1674.76 [#/sec] (mean)
    //使用一键协程 ab -n 1000 -c 10  result: 1996.80 [#/sec] (mean)
//    $dsn="mysql:host=127.0.0.1:5141;dbname=test";
//    $pdo = new PDO($dsn, 'root', 'Wang659096.'); //初始化一个PDO对象
//    $sql = "select * from hd_logs where title='APP-PC:微信支付.1' limit 1";
//    $result = $pdo->query($sql);
//    $list = $result->fetchAll();

    //mysql 协程客户端 ab -n 1000 -c 10  result: 2292.62 [#/sec] (mean)
//    $swoole_mysql = new Swoole\Coroutine\MySQL();
//    $swoole_mysql->connect([
//        'host'     => '127.0.0.1',
//        'port'     => 5141,
//        'user'     => 'root',
//        'password' => 'Wang659096.',
//        'database' => 'test',
//    ]);

    //pdo mysql 连接池 ab -n 1000 -c 10  result:3550.24 [#/sec] (mean)
    $pdo       = $pool->get();
    $statement = $pdo->query("select * from hd_logs where title='APP-PC:微信支付.1' limit 1");
    $res       = $statement->fetchAll();

    $pool->put($pdo);
    
    $response->end('Hello Swoole' . $res[0]['content'] . PHP_EOL);
});

$http->start();